<template>
  <div class="sales-charts-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>销售趋势与图表分析</h3>
          <div class="header-actions">
            <el-button type="primary" @click="refreshCharts">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-button type="success" @click="exportCharts">
              <el-icon><Download /></el-icon>
              导出图表
            </el-button>
            <el-button type="warning" @click="showChartSettings">
              <el-icon><Setting /></el-icon>
              图表设置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 时间范围选择 -->
      <div class="time-range-selector">
        <el-form inline>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleTimeRangeChange"
            />
          </el-form-item>
          <el-form-item label="时间粒度">
            <el-select v-model="timeGranularity" @change="handleGranularityChange">
              <el-option label="按小时" value="hour" />
              <el-option label="按天" value="day" />
              <el-option label="按周" value="week" />
              <el-option label="按月" value="month" />
            </el-select>
          </el-form-item>
          <el-form-item label="对比期间">
            <el-select v-model="comparePeriod" @change="handleCompareChange">
              <el-option label="无对比" value="none" />
              <el-option label="同比" value="year" />
              <el-option label="环比" value="period" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 图表网格 -->
      <div class="charts-grid">
        <!-- 销售趋势图 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>销售趋势分析</span>
              <div class="chart-controls">
                <el-radio-group v-model="trendChartType" @change="updateTrendChart">
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                  <el-radio-button label="area">面积图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="trendChartRef"></div>
        </el-card>

        <!-- 商品销售排行 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>商品销售排行</span>
              <div class="chart-controls">
                <el-select v-model="productRankingLimit" @change="updateProductChart">
                  <el-option label="前5名" :value="5" />
                  <el-option label="前10名" :value="10" />
                  <el-option label="前20名" :value="20" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="productChartRef"></div>
        </el-card>

        <!-- 支付方式分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>支付方式分布</span>
              <div class="chart-controls">
                <el-radio-group v-model="paymentChartType" @change="updatePaymentChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="doughnut">环形图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="paymentChartRef"></div>
        </el-card>

        <!-- 收银员业绩对比 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>收银员业绩对比</span>
              <div class="chart-controls">
                <el-radio-group v-model="cashierChartType" @change="updateCashierChart">
                  <el-radio-button label="bar">柱状图</el-radio-button>
                  <el-radio-button label="radar">雷达图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="cashierChartRef"></div>
        </el-card>

        <!-- 时段销售分析 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>时段销售分析</span>
              <div class="chart-controls">
                <el-radio-group v-model="hourlyChartType" @change="updateHourlyChart">
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="hourlyChartRef"></div>
        </el-card>

        <!-- 客户分析 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>客户分析</span>
              <div class="chart-controls">
                <el-radio-group v-model="customerChartType" @change="updateCustomerChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="funnel">漏斗图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="customerChartRef"></div>
        </el-card>
      </div>
    </el-card>

    <!-- 图表设置对话框 -->
    <el-dialog
      v-model="chartSettingsVisible"
      title="图表设置"
      width="600px"
    >
      <el-form :model="chartSettings" label-width="120px">
        <el-form-item label="图表主题">
          <el-select v-model="chartSettings.theme" @change="updateAllCharts">
            <el-option label="默认主题" value="default" />
            <el-option label="商务主题" value="business" />
            <el-option label="科技主题" value="tech" />
            <el-option label="清新主题" value="fresh" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="颜色方案">
          <el-select v-model="chartSettings.colorScheme" @change="updateAllCharts">
            <el-option label="经典蓝" value="blue" />
            <el-option label="活力橙" value="orange" />
            <el-option label="自然绿" value="green" />
            <el-option label="优雅紫" value="purple" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="动画效果">
          <el-switch v-model="chartSettings.animation" @change="updateAllCharts" />
        </el-form-item>
        
        <el-form-item label="显示网格">
          <el-switch v-model="chartSettings.showGrid" @change="updateAllCharts" />
        </el-form-item>
        
        <el-form-item label="显示图例">
          <el-switch v-model="chartSettings.showLegend" @change="updateAllCharts" />
        </el-form-item>
        
        <el-form-item label="显示数据标签">
          <el-switch v-model="chartSettings.showDataLabel" @change="updateAllCharts" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="chartSettingsVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChartSettings">保存设置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 响应式数据
const timeRange = ref([])
const timeGranularity = ref('day')
const comparePeriod = ref('none')
const chartSettingsVisible = ref(false)

// 图表类型
const trendChartType = ref('line')
const productRankingLimit = ref(10)
const paymentChartType = ref('pie')
const cashierChartType = ref('bar')
const hourlyChartType = ref('line')
const customerChartType = ref('pie')

// 图表设置
const chartSettings = reactive({
  theme: 'default',
  colorScheme: 'blue',
  animation: true,
  showGrid: true,
  showLegend: true,
  showDataLabel: false
})

// 图表引用
const trendChartRef = ref()
const productChartRef = ref()
const paymentChartRef = ref()
const cashierChartRef = ref()
const hourlyChartRef = ref()
const customerChartRef = ref()

// 图表实例
let trendChart = null
let productChart = null
let paymentChart = null
let cashierChart = null
let hourlyChart = null
let customerChart = null

// 模拟数据
const mockData = {
  trend: {
    dates: ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07'],
    sales: [12000, 15000, 18000, 16000, 20000, 22000, 19000],
    orders: [85, 102, 125, 98, 140, 156, 128],
    customers: [78, 95, 118, 89, 132, 145, 115]
  },
  products: [
    { name: '可口可乐', value: 1560, amount: 5460 },
    { name: '洗发水', value: 450, amount: 13455 },
    { name: 'Nike运动鞋', value: 120, amount: 10788 },
    { name: 'iPhone 15', value: 30, amount: 17997 },
    { name: 'MacBook Pro', value: 10, amount: 12999 }
  ],
  payments: [
    { name: '现金支付', value: 15680.50, percentage: 25.2 },
    { name: '刷卡支付', value: 23400.00, percentage: 37.6 },
    { name: '支付宝', value: 18900.00, percentage: 30.4 },
    { name: '微信支付', value: 4200.00, percentage: 6.8 }
  ],
  cashiers: [
    { name: '收银员001', sales: 15680.50, orders: 89, efficiency: 4.5, customers: 78 },
    { name: '收银员002', sales: 10000.00, orders: 67, efficiency: 4.2, customers: 65 },
    { name: '收银员003', sales: 8500.00, orders: 45, efficiency: 4.8, customers: 42 }
  ],
  hourly: [
    { hour: '08:00', sales: 1200, orders: 8 },
    { hour: '09:00', sales: 1800, orders: 12 },
    { hour: '10:00', sales: 2200, orders: 15 },
    { hour: '11:00', sales: 2000, orders: 14 },
    { hour: '12:00', sales: 1600, orders: 11 },
    { hour: '13:00', sales: 1400, orders: 10 },
    { hour: '14:00', sales: 1900, orders: 13 },
    { hour: '15:00', sales: 2100, orders: 14 },
    { hour: '16:00', sales: 2300, orders: 16 },
    { hour: '17:00', sales: 2500, orders: 17 },
    { hour: '18:00', sales: 2800, orders: 19 },
    { hour: '19:00', sales: 2600, orders: 18 },
    { hour: '20:00', sales: 2000, orders: 14 },
    { hour: '21:00', sales: 1500, orders: 10 }
  ],
  customers: [
    { name: '新客户', value: 156, percentage: 21.0 },
    { name: '回头客', value: 234, percentage: 31.5 },
    { name: 'VIP客户', value: 189, percentage: 25.5 },
    { name: '普通客户', value: 163, percentage: 22.0 }
  ]
}

// 方法
const handleTimeRangeChange = () => {
  updateAllCharts()
}

const handleGranularityChange = () => {
  updateAllCharts()
}

const handleCompareChange = () => {
  updateAllCharts()
}

const updateTrendChart = () => {
  if (!trendChart) return
  
  const option = {
    title: {
      text: '销售趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['销售额', '订单数', '客户数'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: mockData.trend.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '数量',
        position: 'right'
      }
    ],
    series: [
      {
        name: '销售额',
        type: trendChartType.value,
        data: mockData.trend.sales,
        smooth: true,
        areaStyle: trendChartType.value === 'area' ? {} : null
      },
      {
        name: '订单数',
        type: trendChartType.value,
        yAxisIndex: 1,
        data: mockData.trend.orders,
        smooth: true
      },
      {
        name: '客户数',
        type: trendChartType.value,
        yAxisIndex: 1,
        data: mockData.trend.customers,
        smooth: true
      }
    ],
    animation: chartSettings.animation
  }
  
  trendChart.setOption(option)
}

const updateProductChart = () => {
  if (!productChart) return
  
  const data = mockData.products.slice(0, productRankingLimit.value)
  
  const option = {
    title: {
      text: '商品销售排行',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '销售数量'
    },
    series: [
      {
        name: '销售数量',
        type: 'bar',
        data: data.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ],
    animation: chartSettings.animation
  }
  
  productChart.setOption(option)
}

const updatePaymentChart = () => {
  if (!paymentChart) return
  
  let option = {}
  
  if (paymentChartType.value === 'pie' || paymentChartType.value === 'doughnut') {
    option = {
      title: {
        text: '支付方式分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '支付方式',
          type: 'pie',
          radius: paymentChartType.value === 'doughnut' ? ['40%', '70%'] : '70%',
          data: mockData.payments,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ],
      animation: chartSettings.animation
    }
  } else {
    option = {
      title: {
        text: '支付方式分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: mockData.payments.map(item => item.name)
      },
      yAxis: {
        type: 'value',
        name: '金额(元)'
      },
      series: [
        {
          name: '支付金额',
          type: 'bar',
          data: mockData.payments.map(item => item.value)
        }
      ],
      animation: chartSettings.animation
    }
  }
  
  paymentChart.setOption(option)
}

const updateCashierChart = () => {
  if (!cashierChart) return
  
  let option = {}
  
  if (cashierChartType.value === 'radar') {
    option = {
      title: {
        text: '收银员业绩对比',
        left: 'center'
      },
      tooltip: {},
      legend: {
        data: mockData.cashiers.map(item => item.name),
        top: 30
      },
      radar: {
        indicator: [
          { name: '销售额', max: 20000 },
          { name: '订单数', max: 100 },
          { name: '效率评分', max: 5 },
          { name: '客户数', max: 100 }
        ]
      },
      series: [
        {
          name: '收银员业绩',
          type: 'radar',
          data: mockData.cashiers.map(item => [
            item.sales,
            item.orders,
            item.efficiency,
            item.customers
          ])
        }
      ],
      animation: chartSettings.animation
    }
  } else {
    option = {
      title: {
        text: '收银员业绩对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['销售额', '订单数'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: mockData.cashiers.map(item => item.name)
      },
      yAxis: [
        {
          type: 'value',
          name: '销售额(元)',
          position: 'left'
        },
        {
          type: 'value',
          name: '订单数',
          position: 'right'
        }
      ],
      series: [
        {
          name: '销售额',
          type: 'bar',
          data: mockData.cashiers.map(item => item.sales)
        },
        {
          name: '订单数',
          type: 'bar',
          yAxisIndex: 1,
          data: mockData.cashiers.map(item => item.orders)
        }
      ],
      animation: chartSettings.animation
    }
  }
  
  cashierChart.setOption(option)
}

const updateHourlyChart = () => {
  if (!hourlyChart) return
  
  const option = {
    title: {
      text: '时段销售分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['销售额', '订单数'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: mockData.hourly.map(item => item.hour)
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '销售额',
        type: hourlyChartType.value,
        data: mockData.hourly.map(item => item.sales),
        smooth: true
      },
      {
        name: '订单数',
        type: hourlyChartType.value,
        yAxisIndex: 1,
        data: mockData.hourly.map(item => item.orders),
        smooth: true
      }
    ],
    animation: chartSettings.animation
  }
  
  hourlyChart.setOption(option)
}

const updateCustomerChart = () => {
  if (!customerChart) return
  
  let option = {}
  
  if (customerChartType.value === 'pie') {
    option = {
      title: {
        text: '客户分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '客户类型',
          type: 'pie',
          radius: '70%',
          data: mockData.customers,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ],
      animation: chartSettings.animation
    }
  } else {
    option = {
      title: {
        text: '客户分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      series: [
        {
          name: '客户类型',
          type: 'funnel',
          left: '10%',
          top: 60,
          bottom: 60,
          width: '80%',
          min: 0,
          max: 100,
          minSize: '0%',
          maxSize: '100%',
          sort: 'descending',
          gap: 2,
          label: {
            show: true,
            position: 'inside'
          },
          labelLine: {
            length: 10,
            lineStyle: {
              width: 1,
              type: 'solid'
            }
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 20
            }
          },
          data: mockData.customers
        }
      ],
      animation: chartSettings.animation
    }
  }
  
  customerChart.setOption(option)
}

const updateAllCharts = () => {
  updateTrendChart()
  updateProductChart()
  updatePaymentChart()
  updateCashierChart()
  updateHourlyChart()
  updateCustomerChart()
}

const initCharts = async () => {
  await nextTick()
  
  // 初始化所有图表
  trendChart = echarts.init(trendChartRef.value)
  productChart = echarts.init(productChartRef.value)
  paymentChart = echarts.init(paymentChartRef.value)
  cashierChart = echarts.init(cashierChartRef.value)
  hourlyChart = echarts.init(hourlyChartRef.value)
  customerChart = echarts.init(customerChartRef.value)
  
  // 设置初始选项
  updateAllCharts()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  if (trendChart) trendChart.resize()
  if (productChart) productChart.resize()
  if (paymentChart) paymentChart.resize()
  if (cashierChart) cashierChart.resize()
  if (hourlyChart) hourlyChart.resize()
  if (customerChart) customerChart.resize()
}

const refreshCharts = () => {
  updateAllCharts()
  ElMessage.success('图表数据已刷新')
}

const exportCharts = () => {
  ElMessage.success('图表导出成功')
}

const showChartSettings = () => {
  chartSettingsVisible.value = true
}

const saveChartSettings = () => {
  localStorage.setItem('chartSettings', JSON.stringify(chartSettings))
  updateAllCharts()
  chartSettingsVisible.value = false
  ElMessage.success('图表设置已保存')
}

// 生命周期
onMounted(() => {
  // 设置默认时间范围
  const today = new Date()
  const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  timeRange.value = [
    lastWeek.toISOString().split('T')[0],
    today.toISOString().split('T')[0]
  ]
  
  // 加载保存的设置
  const saved = localStorage.getItem('chartSettings')
  if (saved) {
    Object.assign(chartSettings, JSON.parse(saved))
  }
  
  // 初始化图表
  initCharts()
})

onUnmounted(() => {
  // 清理图表实例
  if (trendChart) trendChart.dispose()
  if (productChart) productChart.dispose()
  if (paymentChart) paymentChart.dispose()
  if (cashierChart) cashierChart.dispose()
  if (hourlyChart) hourlyChart.dispose()
  if (customerChart) customerChart.dispose()
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.sales-charts-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.time-range-selector {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header span {
  font-weight: 600;
  color: #303133;
}

.chart-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .time-range-selector .el-form {
    flex-direction: column;
  }
  
  .time-range-selector .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .chart-controls {
    justify-content: center;
  }
  
  .chart-container {
    height: 300px;
  }
}
</style>
